<template>
  <div class="home">
    <div class="title-container" v-if="permersion.search">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入用户姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >
            搜索</el-button
          >
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="medium"
          @click="handlerAccount"
          v-if="permersion.add"
        >
          新建角色</el-button
        >
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
          >刷新</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        class="elTable"
        ref="tableRef"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="roleName" label="角色名称" align="center" />
        <el-table-column prop="roleDes" label="角色描述" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="{ row }">
            <el-button type="warning" size="mini" @click="handlerEdit(row)"
              >编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handlerDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="pagination"
      />
    </el-card>
    <!-- 弹框 -->

    <yc-dialog ref="ycDialog" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="loginFormRef"
            :model="newAccountModel"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="newAccountModel.roleName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input
                v-model="newAccountModel.roleDes"
                :disabled="detailsDisabled"
              />
            </el-form-item>
          </el-form>
          <div class="table">
            <el-table
              ref="multipleTable"
              :data="tableData2"
              tooltip-effect="dark"
              style="width: 100%"
              @select="select"
              @select-all="selectAll"
              @selection-change="handleSelectionChange"
              :tree-props="{
                label: 'menuName',
                children: 'children',
                hasChildren: 'hasChildren'
              }"
              row-key="id"
              :select-on-indeterminate="true"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="menuName" label="菜单名称" width="220">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false"
          >取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
import { accountConfig } from "@/config/account"
import {
  queryRolePage,
  queryOneRole,
  updateRole,
  insertRole,
  deleteRole
} from "@/api/userControl/role"
import ycDialog from "@/components/pageDialog"
export default {
  data() {
    return {
      isGlobalMessageShow: false,
      isGlobalMessageBoxShow: false,
      messageTitleDes: "",
      message: "",
      messageBoxSaveShow: false,
      accountConfig,
      tableData: [],
      count: 0,
      pageIndex: 1,
      pageSize: 20,
      count2: 10,
      pageIndex2: 1,
      pageSize2: 20,
      drawerTitle: "账户详情",
      detailsDisabled: false, //详情 如果为true代表禁用状态
      selectOptions: [
        {
          label: "正常/停用状态（全部）",
          value: null
        },
        {
          label: "正常",
          value: 1
        },
        {
          label: "禁用",
          value: 0
        }
      ],
      searchModel: {
        userName: "",
        status: "" //正常/停用状态（全部）
      },

      newAccountModel: {
        roleName: "",
        roleDes: "",
        roleCode: ""
      },
      centerTitle: "",
      permersion: {
        add: true,
        del: true,
        update: true,
        search: true
      },
      loading: false,
      tableData2: [],
      multipleSelection: [],
      editorId: "",
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      }
    }
  },
  components: {
    ycDialog
  },
  created() {
    this.getAccountData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
     * 获取表格方法
     */
    async getAccountData(pageIndex = 1, pageSize = 20, tableInfo) {
      this.loading = true
      if (tableInfo) {
        const { userName, status } = tableInfo
        const { object } = await queryRolePage({
          pageIndex,
          pageSize,
          roleName: userName
        })
        this.tableData = object.data
        this.count = object.count
        this.loading = false
      } else {
        const { object } = await queryRolePage({
          pageIndex,
          pageSize
        })
        this.tableData = object.data
        this.count = object.count
        this.loading = false
      }
    },
    pagination(pageItem) {
      this.getAccountData(pageItem.page, pageItem.limit)
    },
    pagination2(pageItem) {
      this.queryOneRole(pageItem.page, pageItem.limit)
    },
    /**
     * 修改按钮
     */
    async handlerEdit(row) {
      this.centerTitle = "编辑"
      this.editorId = row.id
      await this.queryOneRole(row)
      this.$refs.ycDialog.dialogVisible = true
      this.$refs.loginFormRef?.clearValidate()
      this.detailsDisabled = false
      this.newAccountModel.roleName = row.roleName
      this.newAccountModel.roleCode = row.roleCode
      this.newAccountModel.roleDes = row.roleDes
    },
    async queryOneRole(val) {
      const params = {
        pageIndex: this.pageIndex2,
        pageSize: this.pageSize2,
        roleCode: val?.roleCode
      }
      const data = await queryOneRole(params)
      this.tableData2 = data.object.menu
      console.log(this.tableData2)
      this.checkShow(data.object.menu, true)
    },
    checkShow(data, isShow) {
      data.forEach((e) => {
        if (e.messages == "1") {
          setTimeout(() => {
            this.$refs.multipleTable.toggleRowSelection(e, isShow)
            if (e.children?.length) {
              e.children.forEach((v) => {
                if (v.messages == "1") {
                  this.$refs.multipleTable.toggleRowSelection(v, isShow)
                }
              })
            }
          })
        }
      })
    },
    /**
     * 删除按钮
     */
    async handlerDelete({ id }) {
      this.$confirm("确定删除此角色吗", "删除操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
        center: true
      }).then(async () => {
        const { message } = await deleteRole({ id })
        if (message == "删除成功") {
          this.getAccountData()
          this.isGlobalMessageShow = true
          this.message = "success"
        } else {
          this.message = "error"
        }
      })
    },

    // 搜索按钮
    async searchClick() {
      this.getAccountData(1, 20, this.searchModel)
    },
    /**
     * 新建账户
     * */
    async handlerAccount() {
      this.centerTitle = "添加"
      this.queryOneRole()
      this.editorId = ""
      this.detailsDisabled = false
      this.$refs.ycDialog.dialogVisible = true
      this.$refs.loginFormRef?.clearValidate()
      Object.keys(this.newAccountModel).forEach((item) => {
        this.newAccountModel[item] = ""
      })
      this.checkShow(this.tableData2, false)
      // this.$refs.multipleTable.clearSelection()
    },
    dialogSave() {
      this.$refs.loginFormRef.validate(async (v) => {
        if (v) {
          const arr = []
          this.multipleSelection.forEach((e) => {
            arr.push(e.id + "-" + "menu")
          })
          const str = arr.join(",")
          console.log(str, "str")
          if (this.detailsDisabled) {
            // 详情的确定
            this.$refs.ycDialog.dialogVisible = false
          } else if (this.editorId) {
            const { roleCode, roleName, roleDes } = this.newAccountModel
            const { message, status } = await updateRole({
              roleCode,
              roleName,
              roleDes,
              menusString: str,
              id: this.editorId
            })
            this.$message.success(message)
            if (status == 200) {
              this.$refs.ycDialog.dialogVisible = false
              this.getAccountData()
            }
          } else {
            const { message, status } = await insertRole({
              ...this.newAccountModel,
              menusString: str
            })
            this.$message.success(message)
            if (status == 200) {
              this.$refs.ycDialog.dialogVisible = false
              this.getAccountData()
            }
          }
        }
      })
    },
    /**
     * 刷新
     */
    refresh() {
      this.searchModel = {}
      this.getAccountData()
    },
    /**
     * globalMessage的知道按钮的方法
     * */
    receive() {
      this.isGlobalMessageShow = false
    },
    async messageBoxSave(show) {
      this.messageBoxSaveShow = show
    },
    setChildren(children, type) {
      console.log(children, 2222)
      // 编辑多个子层级
      children.map((j) => {
        this.toggleSelection(j, type)
        if (j.children?.length) {
          console.log(111111)
          this.setChildren(j.children, type)
        }
      })
    },
    // 选中父节点时，子节点一起选中取消
    select(selection, row) {
      const hasSelect = selection.some((el) => {
        return row.id === el.id
      })
      if (hasSelect) {
        if (row.children) {
          // 解决子组件没有被勾选到
          this.setChildren(row.children, true)
        }
      } else {
        if (row.children) {
          this.setChildren(row.children, false)
        }
      }
    },
    toggleSelection(row, select) {
      console.log(row, "row")
      if (row) {
        this.$nextTick(() => {
          this.$refs.multipleTable &&
            this.$refs.multipleTable.toggleRowSelection(row, select)
        })
      }
    },
    // 选择全部
    selectAll(selection) {
      // console.log(selection, "1111")
      // tabledata第一层只要有在selection里面就是全选
      const isSelect = selection.some((el) => {
        const tableDataIds = this.tableData2.map((j) => j.id)
        return tableDataIds.includes(el.id)
      })
      // tableDate第一层只要有不在selection里面就是全不选
      const isCancel = !this.tableData2.every((el) => {
        const selectIds = selection.map((j) => j.id)
        return selectIds.includes(el.id)
      })
      if (isSelect) {
        selection.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, true)
          }
        })
      }
      if (isCancel) {
        this.tableData2.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, false)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.status {
  display: inline-block;
  padding: 0 10px;
}
.title-container {
  display: flex;
  justify-content: flex-end;
  height: 60px;
  .search-content {
    margin: 10px 20px;
    display: flex;
  }
  .addAccount {
    margin: 10px 20px;
  }
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.content {
  height: 600px;

  .drawer-title {
    font-weight: 400;
    font-size: 24px;
    color: #000000;
    text-align: center;
    padding: 36px 0;
  }
  .form {
    padding: 0 10px;
  }
}
.footer {
  height: 360px;
  display: flex;
  align-items: flex-end;
  // justify-content: st-end;
  padding: 5px 20px;
}
</style>
